<template>
  <div class="add-btn">
    <el-dialog
      title="新增用户"
      :visible.sync="dialogVisible"
      width="1000px"
      :append-to-body="true"
      @close="closeAddDialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refAddForm"
        label-width="80px"
        :inline="true"
      >
        <div class="titles">
          <div class="ant-col"><span class="red-star">*</span>用户名</div>
          <div class="ant-col"><span class="red-star">*</span>手机号</div>
          <!-- <div class="ant-col"><span class="red-star">*</span>密码</div> -->
          <!-- <div class="ant-col"><span class="red-star">*</span>确认密码</div> -->
          <div class="ant-col" style="width: 240px">
            <span class="red-star">*</span>组织机构
          </div>
          <!-- <div class="ant-col"><span class="red-star">*</span>岗位</div> -->
          <div class="ant-col"><span class="red-star">*</span>用户角色</div>
        </div>
        <div
          v-for="(item, index) in addForm.formData"
          :key="index"
          class="list"
        >
          <el-form-item
            size="small"
            :prop="`formData.${index}.username`"
            :rules="rules.username"
          >
            <el-input
              clearable
              maxlength="18"
              v-model="item.username"
              placeholder="请输入"
              oninput="value=value.replace(/\s*/g,'')"
              @blur="item.username = $event.target.value"
              style="width: 210px"
            ></el-input>
          </el-form-item>

          <el-form-item
            size="small"
            :prop="`formData.${index}.mobile`"
            :rules="rules.mobile"
          >
            <el-input
              clearable
              oninput="value=value.replace(/[^\d]/g,'')"
              @blur="item.mobile = $event.target.value"
              v-model="item.mobile"
              placeholder="请输入"
              maxlength="11"
              style="width: 210px"
            ></el-input>
          </el-form-item>

          <!-- <el-form-item
            size="small"
            :prop="`formData.${index}.passWord`"
            :rules="rules.passWord"
          >
            <el-input
              clearable
              v-model="item.passWord"
              placeholder="请输入密码"
              show-password
              autocomplete="off"
              oninput="value=value.replace(/\s*/g,'')"
              maxlength="16"
              readOnly
              @input.native="onInput($event, item.passWord)"
              @mousedown.native="onMousedown"
              style="width: 160px"
            ></el-input>
          </el-form-item> -->

          <!-- <el-form-item size="small" prop="verifyPassWord" >
              <el-input
                clearable
                v-model="addForm.formData.verifyPassWord"
                placeholder="请输入密码"
                show-password
                autocomplete="off"
                oninput="value=value.replace(/\s*/g,'')"
                maxlength="16"
                readOnly
                @input.native="onInput($event, addForm.formData.verifyPassWord)"
                @mousedown.native="onMousedown"
                style="width: 150px"
              ></el-input>
            </el-form-item> -->

          <!-- <el-form-item
            size="small"
            :prop="`formData.${index}.orgRole`"
            :rules="rules.orgRole"
          >
            <el-select
              v-model="item.orgRole"
              placeholder="请选择岗位"
              style="width: 150px"
            >
              <el-option
                v-for="item in orgRoleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item
            size="small"
            :prop="`formData.${index}.orgIdList`"
            :rules="rules.orgIdList"
          >
            <!-- <treeselect style="width: 230px" v-model="item.orgIdList" :options="dataList" :normalizer="normalizer"
              :load-options="loadOptions" placeholder="请选择组织机构" @input="changeOrgId($event, index)" :clearable="false"
              noChildrenText="加载中..." noOptionsText="暂无组织机构" noResultsText="无匹配数据" :multiple="true" collapse-tags
              :hideNodePathLabel="true" :appendToBody="true" z-index="9000" :limit="1" :limitText="count => `+${count}`"
              :searchable="false" /> -->

            <el-input
              @focus="onfocus(index)"
              v-model="item.orgName"
              placeholder="请选择"
              style="width: 100%"
            ></el-input>
          </el-form-item>

          <el-form-item
            size="small"
            :prop="`formData.${index}.roleId`"
            :rules="rules.roleId"
          >
            <el-select
              v-model="item.roleId"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.description"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <i
            class="el-icon-delete icon"
            @click="clickDel(index)"
            v-if="addForm.formData.length > 1"
          ></i>
          <i
            class="el-icon-circle-plus-outline icon"
            @click="clickAdd()"
            v-if="index === addForm.formData.length - 1"
          ></i>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAddDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="addSubmit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      width="600px"
      title="选择组织"
      :visible.sync="innerVisible"
      append-to-body
    >
      <div style="min-height: 55vh">
        <!-- check-strictly @check="onCheck"-->
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          ref="treeRef"
          check-strictly
          :default-checked-keys="defaultList"
          :expand-on-click-node="false"
        >
        </el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closetree" class="cancel-button"
          >取 消</el-button
        >
        <el-button size="small" @click="addtree" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { handleTree, transTree } from "@utils/trans-tree";
import { addUser, reqOrgList } from "@/api/api";
import { validateUsername, validatePass, validMobile } from "@utils/validate";
import { mapState } from "vuex";
import mixinPwd from "@utils/mixin/PreBrowserDefaultPassPop";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";

export default {
  name: "addUser",
  props: ["roleList", "enterpriseList", "orgName2", "fixedPjtInfo"],
  mixins: [mixinPwd, tableStyleMixin],
  components: { treeselect, Pagination },
  data() {
    var checkPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.passWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      expandedKeys: false,
      page: 1,
      limit: 5,
      total: 0,
      // orgIdList:[],//组织机构id集
      isRadio: false,
      dialogVisible: false, //弹框是否显示
      addForm: {
        formData: [
          {
            username: "",
            passWord: "",
            verifyPassWord: "",
            mobile: "",
            nickname: "",
            roleId: "", // 角色id
            enterpriseId: "",
            // orgId: null, //组织机构id
            orgIdList: [], //组织机构id集
            orgRole: "",
            orgName: "",
          },
        ],
      },
      orgRoleList: [
        {
          id: 2,
          name: "消防安全专员",
        },
        {
          id: 3,
          name: "消防安全负责人",
        },
        {
          id: 4,
          name: "消防监管人",
        },
        {
          id: 5,
          name: "专职消防安全管理人",
        },
        {
          id: 6,
          name: "楼(建筑)长",
        },
        {
          id: 7,
          name: "维保人员",
        },
      ],
      projectList: [], //组织机构数据
      projectPage: 1,
      projectLimit: 10,
      projectTotal: 0,
      // 表单修改验证信息
      rules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 位",
            trigger: "blur",
          },
        ],
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            validator: validateUsername,
          },
        ],
        passWord: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            validator: validatePass,
          },
        ],
        verifyPassWord: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            validator: checkPass,
          },
        ],
        imageCode: [
          {
            required: true,
            message: "请输入图形验证码",
            trigger: "blur",
          },
        ],
        smsCode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: validMobile,
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          },
        ],
        orgIdList: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
        orgRole: [
          {
            required: true,
            message: "请选择岗位",
            trigger: ["blur", "change"],
          },
        ],
        enterpriseId: [
          {
            required: true,
            message: "请选择租户",
            trigger: ["blur", "change"],
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
      },
      isThreeTeams: window.sessionStorage.getItem("threeTeams"),
      loadingSearch: false,
      defaultProps: {
        children: "children",
        label: "orgName",
        isLeaf: "hasChildren",
        id: "id",
      },
      treeData: [],
      // 选择的数据
      iconId: "",
      parentCheckedId: 0,
      typeId: 0,
      // 选择的数据
      parentIdList: [],
      isTree: true,
      dataList: [],
      innerVisible: false,
      orgName: "",
      defaultList: [],
    };
  },
  computed: {
    ...mapState(["companyId", "user", "spacesManage"]),
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.addForm.formData[0].orgName = this.orgName2;
        this.addForm.formData[0].orgIdList = [this.fixedPjtInfo.orgId];
        // console.log(this.addForm);
        // console.log(this.orgName2);
      }
    },
  },
  methods: {
    handleCheckChange(data, checked) {
      if (data.children) {
        // 如果是父节点，勾选所有子节点，但只记录父节点 ID
        this.$refs.tree.setCheckedKeys([data.id]);
        this.selectedIds = [data.id];
      } else {
        // 如果是子节点，不勾选父节点，只记录子节点 ID
        this.selectedIds = this.$refs.tree.getCheckedKeys();
      }
    },
    onfocus(index) {
      this.dataList = [];
      this.OrgList();
      this.indexof = index;
      // 赋值
      this.innerVisible = true;
      this.defaultList = this.addForm.formData[index].orgIdList;
      // console.log(this.defaultList, "this.defaultList");
    },
    addtree() {
      const checkedNodes = this.$refs.treeRef.getCheckedNodes();
      this.addForm.formData[this.indexof].orgName = checkedNodes
        .map((node) => node.orgName)
        .join("，");
      // 提取选中节点的 id
      this.addForm.formData[this.indexof].orgIdList = checkedNodes.map(
        (node) => node.id
      );
      this.innerVisible = false;
    },
    closetree() {
      this.innerVisible = false;
      this.defaultList = [];
    },
    // 选择一条
    changeOrgId(id, index) {
      // console.log(id, index, "id");
      this.addForm.formData[index].orgIdList = id;
    },
    // 点击删除
    clickDel(index) {
      this.addForm.formData.splice(index, 1);
    },
    // 点击新增
    clickAdd() {
      if (this.addForm.formData.length >= 10)
        return this.$modal.notifyWarning("一次性添加用户最多10条！");
      this.addForm.formData.push({
        username: "",
        passWord: "",
        verifyPassWord: "",
        mobile: "",
        nickname: "",
        roleId: "", // 角色id
        enterpriseId: "",
        orgIdList: [this.orgId], //组织机构id集
        orgRole: "",
        orgName: this.orgName2,
      });
    },
    getSimpleCheckedNodeIds(originData) {
      // 定义数组
      const checkedNodeIds = [];
      // 判断是否为全选，若为全选状态返回被选中的父节点数据，不为全选状态正常返回被选中的子节点的数据
      const isAllChecked = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          // console.log(child, "child");
          if (child.checked) {
            checkedNodeIds.push(child.data);
          }
          if (child.indeterminate) {
            isAllChecked(child);
          }
        });
      };
      isAllChecked(originData);
      // console.log(checkedNodeIds, "checkedNodeIds");
      return checkedNodeIds;
    },
    // 限制全选按钮
    selectAll() {
      if (this.addForm.roleId === "") {
        this.$refs.refTable.clearSelection();
        this.$modal.notifyWarning("请先选择角色");
        return;
      }
    },
    // 点击获取图形验证码
    async reqVerification() {
      const res = await reqImageCode();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$nextTick(() => {
        this.imageCodeSrc = res.data.imageCode;
      });
    },
    // 点击获取手机验证码
    async getSmsCode() {
      let { mobile, imageCode } = this.addForm;
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!mobile) return this.$modal.notifyWarning("请先填写手机号");
      if (!reg.test(mobile))
        return this.$modal.notifyWarning("请输入正确的手机号");
      if (!imageCode) return this.$modal.notifyWarning("请先填写图形验证码");
      const res = await reqSmsCode({
        imageCode: this.addForm.imageCode,
        mobile: this.addForm.mobile,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifyWarning("请注意查收手机短信验证码");
      this.showCountDown = false;
      this.countDown = 60;
      this.isNext = false;
      let intervalId = setInterval(() => {
        if (this.countDown > 0 && this.countDown <= 60) {
          this.countDown--;
        } else {
          this.showCountDown = true;
          clearInterval(intervalId);
          intervalId = null;
        }
      }, 1000);
    },
    // 获取组织机构列表
    async OrgList() {
      this.dataList = [];
      var res = await reqOrgList( {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgName: "",
        parentId: "",
         type:"1,2,3"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows } = res.data;
      this.dataList = transTree(rows);//返回全部数据
    },
    checkUsernameRepeat(formData) {
      const usernames = formData
        .map((item) => item.username)
        .filter((item) => item !== "");
      const uniqueUsernames = new Set(usernames);
      if (usernames.length !== uniqueUsernames.size) {
        return true; // 有重复的username
      } else {
        return false; // 没有重复的username
      }
    },
    checkMobileRepeat(formData) {
      const mobiles = formData
        .map((item) => item.mobile)
        .filter((item) => item !== "");
      const uniqueUsernames = new Set(mobiles);
      if (mobiles.length !== uniqueUsernames.size) {
        return true; // 有重复的mobile
      } else {
        return false; // 没有重复的mobile
      }
    },
    // 新增按钮
    addSubmit() {
      this.$refs.refAddForm.validate(async (valid) => {
        if (!valid) return;
        // let orgList = this.getSimpleCheckedNodeIds(this.$refs.refTree.store);
        // if (this.user.roleName === "TENANT_ADMIN") {
        //   if (orgList.length < 1)
        //     return this.$modal.notifyWarning("请选择一个组织机构"); //组织机构人员必须选择一个项目
        // }
        if (this.checkUsernameRepeat(this.addForm.formData))
          return this.$modal.notifyWarning("用户名不能重复");
        if (this.checkMobileRepeat(this.addForm.formData))
          return this.$modal.notifyWarning("手机号不能重复");
        this.addForm.formData.forEach((item) => {
          item.verifyPassWord = "";
          item.tenantId = this.user.tenantId;
        });
        const res = await addUser({
          userAddList: this.addForm.formData,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$alert("新增用户成功，账号可通过手机短信验证码登录", "温馨提示", {
          confirmButtonText: "确定",
          type: "success",
          callback: (action) => {
            this.$parent.getInitDataList(); //更新列表
            this.closeAddDialog();
          },
        });
      });
    },
    // 点击取消和关闭按钮 （ 清除验证  关闭弹窗）
    closeAddDialog() {
      (this.addForm = {
        formData: [
          {
            username: "",
            passWord: "",
            verifyPassWord: "",
            mobile: "",
            nickname: "",
            roleId: "", // 角色id
            enterpriseId: "",
            orgIdList: [], //组织机构id集
            orgRole: "",
          },
        ],
      }),
        this.$refs.refAddForm.resetFields();
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if (this.$refs.refTable != null || this.$refs.refAddForm != null) {
      this.closeAddDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../../common.less");

.form-style {
  // display: flex;
  // flex-wrap: wrap;
  // justify-content: space-evenly;
  width: 100%;
}

/deep/ .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 26px;
}

// 分页器
::v-deep .el-pager {
  border-radius: 30px;
  background: @paginationBgcolor;
  margin: 0 5px;
  height: 32px;
}

::v-deep .el-pager li {
  min-width: 32px !important;
  background: @paginationBgcolor !important;
  color: #b4b7bd !important;
  height: 32px !important;
  line-height: 32px !important;
}

::v-deep .el-pager li.active {
  color: #fff !important;
  border-radius: 30px !important;
  background: #7367f0 !important;
}

::v-deep .el-pager li:first-child {
  border-radius: 30px !important;
}

::v-deep .el-pager li:last-child {
  border-radius: 30px !important;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background: #7367f0 !important;
}

::v-deep .el-tree {
  height: 100%;
  font-size: 14px;
  background: @primaryHeaderBgcolor;
  box-sizing: border-box;
  padding: 12px 10px;
  color: @primaryThemeTxtColor;
  overflow: hidden;
  overflow-y: scroll;
}

::v-deep .el-tree-node__content {
  // padding: 5px 0 !important;
  &:hover {
    background: @paginationBgcolor !important;
    border-radius: 4px;
  }
}

// ::v-deep .el-tree-node.is-current.is-focusable > .el-tree-node__content {
//   background-color: #7367f0 !important;
//   border-radius: 4px;
// }

::v-deep .el-tree-node.is-focusable > .el-tree-node__content {
  padding: 5px 0;
}

// 解决点击白底问题
// ::v-deep .el-tree > .el-tree-node:first-of-type > .el-tree-node__content {
//   background-color: #7367f0 !important;
//   color: #f0f0f0;
// }

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded > .el-tree-node__content {
  background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable > .el-tree-node__content {
  background-color: transparent;
  border-radius: 4px;
}

::v-deep .is-current > .el-tree-node__content > .el-tree-node__label {
  color: #f0f0f0;
}

.ogText {
  color: @primaryThemeTxtColor2;
}

.titles {
  border-bottom: 2px solid @primaryBorderColor;
  margin-bottom: 12px;
  padding-bottom: 5px;
  display: flex;
  font-size: 14px;
  color: @primaryThemeTxtColor2;

  .ant-col {
    width: 220px;

    .red-star {
      color: #f56c6c;
    }
  }
}

.icon {
  cursor: pointer;
  font-size: 23px;
  color: #8074fb;
  margin-top: 5px;
  margin-left: 10px;
}

// treeselect开始
/* placeholder字体颜色 */
::v-deep .vue-treeselect__placeholder {
  color: @primaryTxtcolor2;
}

::v-deep .vue-treeselect__control:hover {
  border: 1px solid @primaryBorder !important;
  /* 设置鼠标移入时的背景色为浅灰色 */
}

::v-deep .vue-treeselect__placeholder {
  color: @primaryThemeTxtColor;
  /* 设置占位符的字体颜色为灰色 */
}

::v-deep .vue-treeselect__menu .vue-treeselect__option {
  color: #606266;
  /* 设置选项的字体颜色为蓝色 */
}

::v-deep .vue-treeselect__single-value {
  color: @primaryContentTxt !important;
}

::v-deep .vue-treeselect__control {
  height: 30px;
  border: 1px solid @primaryBorder;
  box-sizing: border-box;
  color: @primaryContentTxt !important;
  background: @primaryHeaderBgcolor;
}

// 小箭头
::v-deep .vue-treeselect__control-arrow-container {
  display: none;
}

::v-deep .vue-treeselect__multi-value {
  height: 30px;
  margin-bottom: 0;
}

::v-deep .vue-treeselect__multi-value-item-container {
  padding-top: 1px;
}

::v-deep .vue-treeselect__limit-tip {
  padding-top: 0;
  padding-right: 0;
  margin-top: -4px;
}

::v-deep .vue-treeselect__multi-value-item {
  padding: 0;
  border: none;
  color: #fff;
  background: #7367f0;
  margin-top: -3px;
}

::v-deep .vue-treeselect__value-remove {
  color: #fff;
  border-left: none;
}

// ::v-deep .vue-treeselect__multi-value-item-container.vue-treeselect__multi-value-item.vue-treeselect__value-remove:hover {
//   color: @primaryTxtcolor2 !important; /* 鼠标移入时的颜色 */
// }

// treeselect结束----------
</style>
